package com.bjsxt.pool;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TestThreadPool1 {

    public static void main(String[] args) {

        //1.创建线程池
        //线程池中只有一个线程
        //ExecutorService pool = Executors.newSingleThreadExecutor();
        //线程池中有固定数量的线程
        //ExecutorService pool = Executors.newFixedThreadPool(10);
        //线程池中有动态变化数量的线程，可以增加和减少
        ExecutorService pool = Executors.newCachedThreadPool();
        //线程池执行定时任务
        //ExecutorService pool = Executors.newScheduledThreadPool(10);

        //2.使用线程池执行多个Runnable任务
        for (int i = 1; i <= 10; i++) {
            Runnable command = new MyRunnable(i);
            //new Thread(command).start();
            pool.execute(command);
        }

        //3.关闭线程池
        pool.shutdown();
    }
}

class MyRunnable implements Runnable {
    private int i;

    public MyRunnable(int i) {
        this.i = i;
    }

    @Override
    public void run() {
        System.out.println("任务" + i + "开始执行！");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("任务" + i + "执行完毕！");
    }

}
